package vg.modules.project;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import vg.services.main_manager.MainManager;
import vg.services.plugin_manager.event_and_request.event.UIEventModelReset;
import vg.services.plugin_manager.event_and_request.request.UIRequestLoadProject;
import vg.services.plugin_manager.event_and_request.request.UIRequestSaveProject;
import vg.services.plugin_manager.interfaces.IPlugin;
import vg.services.plugin_manager.realization.PluginParameter;

public class StorablePlugin implements IPlugin{
	private JMenuItem saveMenuItem, loadMenuItem;
	private PluginParameter param;
	private JFileChooser fileChooserDialog;
	private String currentProjectPath = null;
	private final static String DEF_LAST_STORABLE_DIR = "PROJECT_STORABLE_LastDir";
	/**
	 * Installer.
	 */
	public void install(final PluginParameter param) throws Exception {
		// init components
		this.param = param;
		this.saveMenuItem = new JMenuItem("Save project[not available]");
		this.loadMenuItem = new JMenuItem("Load project[not available]");
		this.saveMenuItem.setEnabled(false);
		this.loadMenuItem.setEnabled(false);
		this.fileChooserDialog = new JFileChooser();
		this.fileChooserDialog.setFileFilter(new FileFilter() {
			public String getDescription() {				
				return "vg file (*.vg)";
			}
			public boolean accept(File f) {
				if (f != null) {
					if (f.isDirectory())
						return true;
					return f.getName().toLowerCase().endsWith("vg");
				}
				return false;
			}
		});
		this.fileChooserDialog.setAcceptAllFileFilterUsed(false);
        
		String lastDir = MainManager.config.getProperty(StorablePlugin.DEF_LAST_STORABLE_DIR);
		if(lastDir != null) {
			this.fileChooserDialog.setCurrentDirectory(new File(lastDir));
		}
		final Component parent = param.userInterfaceManager.getMainFrame();
		// Save project
		this.saveMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(currentProjectPath != null) {
					// replace current project
					UIRequestSaveProject requestSaveProject = new UIRequestSaveProject(currentProjectPath, null);
					param.userInterfaceManager.sendRequest(requestSaveProject);
				} else {
					fileChooserDialog.updateUI();
					// generate save request and send it to decoders
					if(fileChooserDialog.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) {
						MainManager.config.setProperty(StorablePlugin.DEF_LAST_STORABLE_DIR, fileChooserDialog.getCurrentDirectory().getAbsolutePath());
						File projDir = fileChooserDialog.getSelectedFile();
						if(projDir.mkdir()) {
							File progSln = new File(projDir.getAbsolutePath() + File.separator + projDir.getName() + ".vg");
							try {
								currentProjectPath = projDir.getAbsolutePath();
								progSln.createNewFile();
								UIRequestSaveProject requestSaveProject = new UIRequestSaveProject(projDir.getAbsolutePath(), null);
								param.userInterfaceManager.sendRequest(requestSaveProject);
							} catch (Exception ex) {
								MainManager.windowMessage.errorMessage("Could not create file\n" + projDir.getPath(), "Error");
							}
						} else {
							MainManager.windowMessage.errorMessage("Could not create file\n" + projDir.getPath(), "Error");
						}
					}
				}
			}
		});
		// Load project
		this.loadMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				fileChooserDialog.updateUI();
				// generate load request and send it to decoders
				if(fileChooserDialog.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
					final File dir = fileChooserDialog.getCurrentDirectory();
					currentProjectPath = dir.getAbsolutePath();
					MainManager.config.setProperty(StorablePlugin.DEF_LAST_STORABLE_DIR, fileChooserDialog.getCurrentDirectory().getAbsolutePath());
					UIRequestLoadProject requestLoadProject = new UIRequestLoadProject(dir.getPath(), null);

                    // TODO FIX ME = need remove model reset event
                    //param.graphDataBase.resetModel();
                    param.userInterfaceManager.sendEvent(new UIEventModelReset());

                    param.userInterfaceManager.sendRequest(requestLoadProject);
				}
			}
		});
		this.saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK));
		this.loadMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK));

		// Add menu items to main menu of program
		this.param.userInterfaceManager.addMenuItem(saveMenuItem, "file");
		this.param.userInterfaceManager.addMenuItem(loadMenuItem, "file");
	}
}
